package logic

import (
	"context"
	"errors"
	"pay-login/models/cache"
	"pay-login/models/mysql"
	"pay-login/pkg"

	"pay-login/payrpc/internal/svc"
	"pay-login/payrpc/payrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *RegisterLogic) Register(in *payrpc.RegisterRequest) (*payrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()

	if in.Captcha != result {
		return nil, errors.New("验证码错误")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()

	if in.SendSms != s {
		return nil, errors.New("验证码错误，请重新输入")
	}

	user := &mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}

	err := user.UserAdd(mysql.DB)
	if err != nil {
		return nil, err
	}

	cache.Rdb.Del(l.ctx, "captcha"+in.Account)
	cache.Rdb.Del(l.ctx, "sendSms"+in.Account)

	return &payrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
